package Internationalization;


import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Load Internationalization of properties.xml file in src/Resources1. To default get language spanish and country Spain
 * @author escabia
 */
public class LoadInternationalization {
    private static ResourceBundle rb;
    private static boolean instanciado = false;
    private static LoadInternationalization li;
    
    /**
     * Method to load internationalization 
     * @param lang give language and country 
     */
    private LoadInternationalization (String [] lang) {
        String language;
        String country;
        Locale locale;

        if (lang.length != 2) {
            language = "es";
            country = "ES";
        }
        else {
            language = lang[0];
            country = lang[1];
        }
        locale = new Locale(language, country);
        rb = ResourceBundle.getBundle("Internationalization.messages", locale);
    }
    
    /**
     * Method to get resource to get language in all classes
     * @return resource Bundle
     */
    public static ResourceBundle getRB(){
        if (!instanciado){
            try {
                File xml = new File("src/Resources1/properties.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(xml);
                NodeList nodes = doc.getElementsByTagName("languages");
                
                Node n = nodes.item(0);
                Element lang = (Element)n;
                
                
                String [] str = new String[2];
                str[0] = lang.getElementsByTagName("lang").item(0).getTextContent();
                str[1] = lang.getElementsByTagName("location").item(0).getTextContent();
                li = new LoadInternationalization(str);
                instanciado = true;
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(LoadInternationalization.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return rb;
    }
}

